const jwt = require("jsonwebtoken");
const { JWT_SECRET } = require("../config/constants");

const verifyToken = (req, res, next) => {
  const token = req.headers.authorization?.split(" ")[1];
  console.log("Received token:", token); // 打印接收到的token，用于调试

  // 检查是否提供了token，如果没有提供则返回错误响应
  if (!token) {
    return res.status(401).json({ success: false, message: "未提供认证令牌" });
  }

  try {
    const decoded = jwt.verify(token, JWT_SECRET);
    req.user = decoded;
    next();
  } catch (error) {
    console.error("Token verification error:", error);
    return res.status(401).json({ success: false, message: "无效的认证令牌" });
  }
};

module.exports = {
  verifyToken,
};
